package com.example.majingze.testthreaddownloading;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;


public class MainActivity extends Activity implements View.OnClickListener{
    private static final String URL = "http://localhost:8080/WebService/resouse/";
    private static final String SD_PATH = "/mnt/sdcard/";
    private static  final int DOWNLOAD_STATE_START = 1001;
    private static final int DOWNLOAD_STATE_PASUE = 1002;
    private static final int DOWNLOAD_STATE_STOP = 1003;

    private ProgressBar progressBar;
    private ImageButton downloadingState;
    private TextView fileInfo;
    private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
    private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();
    private Map<String, TextView> proportionTVs = new HashMap<String, TextView>();

    private int downloadState = DOWNLOAD_STATE_STOP;
    private volatile int pro = 0;
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 200:
                    int value = msg.arg1;
                    progressBar.setProgress(value);
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView(){
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        downloadingState = (ImageButton) findViewById(R.id.downloading);
        downloadingState.setOnClickListener(this);
        fileInfo = (TextView) findViewById(R.id.file_info);
    }
    Runnable task = new Runnable() {
        @Override
        public void run() {
            int max = progressBar.getMax();
            while (pro < max) {
                pro += 1;
                Message msg = new Message();
                msg.what = 200;
                msg.arg1 = pro;
                mHandler.sendMessage(msg);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private void startDownload(){
        String resouceName = "test.zip";
        String urlstr = URL + resouceName;
        String localfile = SD_PATH + resouceName;
        //设置下载线程数为4，这里是我为了方便随便固定的
        String threadcount = "4";
        DownloadTask downloadTask=new DownloadTask(downloadingState);
        downloadTask.execute(urlstr,localfile,threadcount);
    }
    class DownloadTask extends AsyncTask<String, Integer, LoadInfo> {
        Downloader downloader=null;
        View v=null;
        String urlstr=null;
        public DownloadTask(final View v){
            this.v=v;
        }
        @Override
        protected void onPreExecute() {
            ImageButton btn_start=(ImageButton)((View)v.getParent()).findViewById(R.id.downloading);
            btn_start.setBackgroundResource(R.drawable.puse_bg);
        }
        @Override
        protected LoadInfo doInBackground(String... params) {
            urlstr=params[0];
            String localfile=params[1];
            int threadcount=Integer.parseInt(params[2]);
            // 初始化一个downloader下载器
            downloader = downloaders.get(urlstr);
            if (downloader == null) {
                downloader = new Downloader(urlstr, localfile, threadcount, MainActivity.this, mHandler);
                downloaders.put(urlstr, downloader);
            }
            if (downloader.isDownloading())
                return null;
            // 得到下载信息类的个数组成集合
            return downloader.getDownloaderInfos();
        }
        @Override
        protected void onPostExecute(LoadInfo loadInfo) {
            if(loadInfo!=null){
                // 显示进度条
                showProgress(loadInfo, urlstr, v);
                // 调用方法开始下载
                downloader.download();
            }
        }
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.downloading:
                if(downloadState == DOWNLOAD_STATE_STOP){
                    downloadState = DOWNLOAD_STATE_START;
                }else if(downloadState == DOWNLOAD_STATE_START){
                    downloadState = DOWNLOAD_STATE_PASUE;
                }else {
                    downloadState = DOWNLOAD_STATE_START;
                }
                changeDownloadStateIcon();
                break;
        }
    }
    private void changeDownloadStateIcon(){
        if(downloadState == DOWNLOAD_STATE_START){
            startDownload();
            downloadingState.setBackgroundResource(R.drawable.kaload);
        }else if (downloadState == DOWNLOAD_STATE_PASUE){
            pauseDownload();
            downloadingState.setBackgroundResource(R.drawable.puse_bg);
        }else {
            downloadingState.setBackgroundResource(R.drawable.kaload);
        }
    }
    private void showProgress(LoadInfo loadInfo, String url, View v) {
        ProgressBar bar = ProgressBars.get(url);
        TextView proportionTV = proportionTVs.get(url);
        if (bar == null) {
            RelativeLayout layout = (RelativeLayout) v.getParent();
            bar = ((ProgressBar) layout.findViewById(R.id.progressBar));
            bar.setMax(loadInfo.getFileSize());
            bar.setProgress(loadInfo.getComplete());
            int proportion = (int)(loadInfo.getComplete() * 100 / loadInfo.getFileSize());
            ProgressBars.put(url, bar);
        }
    }
    /**
     * 响应暂停下载按钮的点击事件
     */
    public void pauseDownload() {
        LinearLayout layout = (LinearLayout) downloadingState.getParent();
        String urlstr = URL + "test.zip";
        downloaders.get(urlstr).pause();
    }
}
